﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Diagnostics;
using System.Xml;
using System.IO;
using System.ServiceModel.Channels;
using System.Runtime.Serialization.Json;
using System.ServiceModel;
using System.Reflection;
using System.Threading;

namespace Spike.ServiceFramework.ServiceModel.Registration
{
    public class ServiceRegistrationBehavior : RegistrationBehavior
    {
        [ConfigurationProperty("restrictAccess", DefaultValue = true, IsRequired = false)]
        public bool RestrictAccess
        {
            get { return (bool)base["restrictAccess"]; }
            set { base["restrictAccess"] = value; }
        }

        [ConfigurationProperty("accessGranted", IsRequired = false)]
        public ClientApplicationElementCollection AccessGranted
        {
            get { return (ClientApplicationElementCollection)base["accessGranted"]; }
            set { base["accessGranted"] = value; }
        }

        internal void Validate(Message request)
        {
            try
            {
                var client = request.Headers.GetHeader<ClientApplication>(HEADER_APPLICATION, HEADER_NAMESPACE);

                IEnumerable<ClientApplication> applications = AccessGranted.OfType<ClientApplication>();

                if(!applications.Any(c=>c.Name==client.Name && c.Version==client.Version))
                    throw new FaultException<RegistrationServiceFault>(new RegistrationServiceFault {ClientApplication = client, Message = "Client appliation is not registered for access."});
            }
            catch (Exception ex)
            {
                throw new FaultException("Client request failed validation against registered service.  Verify the client has the correct configuration settings.");
            }
        }
    }


}
